package org.chengn.level_middle.context2048;

import java.util.*;

/**
 * @Title: Context2048DFS
 * @Author ChengN
 * @Package org.chengn.level_middle.context2048
 * @Date 2023/12/9 1:39
 * @description: 下一个更大的数值平衡数 DFS
 */
public class Context2048DFS {
    List<Integer> list = new ArrayList<>();
    public int nextBeautifulNumber(int n) {

        for (int i = 1; i <= 6; ++i) {
            dfs(i, new HashMap<>(), 0);
        }

        Collections.sort(list);
        int res = -1;
        for (int i : list) {
            if (i > n) return i;
        }
        return 1224444;
    }

    private void dfs(int i, Map<Integer, Integer> map, int sum) {
        for (int k = i; k <= 6; ++k) {
            sum += i;
            if (sum > 6) break;
            map.put(i, i);
            search(map, 0);
            dfs(k + 1, map, sum);
            sum -= i;
            map.remove(i);
        }
    }

    private void search(Map<Integer, Integer> map, int ans) {
        boolean flag = false;
        for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() == 0) continue;
            flag = true;
            Integer key = entry.getKey();
            map.put(key, entry.getValue() - 1);
            search(map, ans * 10 + key);
            map.put(key, entry.getValue() + 1);
        }
        if (!flag) list.add(ans);
    }

}
